/****************************************************************************
 * Copyright (C) 2012 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "AutoUpdateCheckTask.h"
#include "../../Prompts/PromptWindows.h"
#include "../ChangeLog.h"
#include "../networkops.h"
#include "../svnrev.h"
#include "../http.h"

AutoUpdateCheckTask::AutoUpdateCheckTask()
{
	rev = 0;
	url = "";
	
	ThreadedTaskHandler::Instance()->AddTask(this);
}

void AutoUpdateCheckTask::Execute(void)
{
	while(!IsNetworkInit())
		usleep(100);
	
	struct block file = downloadfile("http://savegame-manager-gx.googlecode.com/svn/branches/Updates/update.xml");
	if (!file.data)
		return;
	
	file.data[file.size-1] = 0;

	char *revPtr = strstr((char*)file.data, "rev=\"");
	if(!revPtr) {
		free(file.data);
		return;
	}
	revPtr += strlen("rev=\"");

	rev = atoi(revPtr);

	if (rev <= GetIntRev()) {
		free(file.data);
		return;
	}

	char *downloadLink = strstr(revPtr, "link=\"");
	if(!downloadLink) {
		free(file.data);
		return;
	}
	downloadLink += strlen("link=\"");

	char *ptr = strchr(downloadLink, '"');
	if(!ptr) {
		free(file.data);
		return;
	}
	*ptr = 0;
	
	free(file.data);
	url = downloadLink;
	
	int choice = 1;
	do
	{
		choice = WindowPrompt(fmt(tr("Update to Rev%i available"), rev), tr("Do you want to update now ?"), (Settings.GodMode || !(Settings.ParentalBlocks & BLOCK_UPDATES)) ? tr("Yes") : NULL, tr("Show Changelog"), tr("Cancel"));
		
		if(choice == 1 && (!Settings.GodMode && (Settings.ParentalBlocks & BLOCK_UPDATES)))
			choice = 2;
		
		if(choice == 1)
		{
			UpdateCheckEnd(this, url);
			return;
		}
		else if (choice == 2)
		{
			ChangeLog Changelog;
			if(!Changelog.Show())
				ShowError(tr("Failed to get the Changelog."));
		}
		
	} while(choice);
	
	UpdateCheckEnd(this, "");
}
